export function useSelection<T extends Record<string, any>>(
  dataSource: any,
  rowKey: keyof T = 'id' // 默认使用 id 字段,
) {
  const selectedKeys = ref([])
  const isAllSelected = ref()
  const isIndeterminate = ref()
  // 当数据源变化时自动清理无效选中项

  // 切换单个选中状态
  const toggleSelection = (id) => {
    const index = selectedKeys.value.findIndex(k =>
      k === id
    )
    if (index > -1) {
      selectedKeys.value.splice(index, 1)
    } else {
      selectedKeys.value.push(id)
    }
    updateSelectionState()
  }

  // 全选/反选
  const toggleAll = () => {
    if (isAllSelected.value) {
      selectedKeys.value = []
    } else {
      selectedKeys.value = dataSource.value.map(item => item[rowKey])
    }
    updateSelectionState()
  }

  // 状态更新方法
  const updateSelectionState = () => {
    const total = dataSource.value.length
    const selectedCount = selectedKeys.value.length;

    isAllSelected.value = total > 0 && selectedCount === total;
    isIndeterminate.value = selectedCount > 0 && selectedCount < total;
  };

  // 数据变化监听
  watch(dataSource, (newData = []) => {
    const validIds = newData.map(item => item[rowKey])

    // 清理无效选中项
    selectedKeys.value = selectedKeys.value.filter(id =>
      validIds.some(validId => validId === id)
    )
    updateSelectionState();
  }, { immediate: true, deep: true });


  return {
    selectedKeys,
    toggleSelection,
    toggleAll,
    isAllSelected,
    isIndeterminate
  };
}
